package com.xof.phonecall.telecom

import android.content.Intent
import android.telecom.Call
import android.telecom.InCallService
import com.xof.phonecall.MyApplication
import com.xof.phonecall.OutgoingCallActivity

class MyCallService : InCallService() {

    override fun onCallAdded(call: Call?) {
        super.onCallAdded(call)

        if (MyCallManager.sCall == null) {
            println("1 MyCallManager: sCall is null")
        }

        println("MyCallService: onCallAdded")
        println(call?.details?.handle?.schemeSpecificPart.toString())

        MyCallManager.sCall = call
        if (MyCallManager.sCall == null) {
            println("2 MyCallManager: sCall is null")
        }

        println(call?.state)
//        MyCallManager.sCall?.registerCallback(object : Call.Callback() {
//            override fun onStateChanged(call: Call?, state: Int) {
//                super.onStateChanged(call, state)
//
//                println("=====onStateChanged:$state")
//            }
//        })

        val gState = call?.state
        if (Call.STATE_RINGING == gState) {
            //来电
            println("拒绝来电...")
            MyCallManager.reject()
            return
        }

        if (MyApplication.outgoingCallActivity == null) {
            println("创建一个新的outgoing activity")
            val intent = Intent(this, OutgoingCallActivity::class.java)
            intent.data = call?.details?.handle
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            startActivity(intent)
        } else {
            println("重置回调")
            MyCallManager.sCall?.unregisterCallback(MyApplication.outgoingCallActivity?.mCallBack)
            MyCallManager.sCall?.registerCallback(MyApplication.outgoingCallActivity?.mCallBack)
//            MyApplication.outgoingCallActivity?.registerCallManagerCallback()
        }
    }

    override fun onCallRemoved(call: Call?) {
        super.onCallRemoved(call)
        MyCallManager.sCall = null;

    }
}